import { Select } from 'antd';
import { useReducer } from 'react';

function noop() { }

export default function DropdownSelect({ field, onLoad, onChange = noop, ...props }) {
  const [state, dispatch] = useReducer((state, action) => {
    return { ...state, ...action }
  }, {
    rows: [],
    options: props.options,
    open: false,
  });

  async function onLoadData() {
    const { Rows } = await onLoad();
    const options = Rows.map(r => ({
      value: r.ID,
      label: r[field],
      title: Object.values(r).join(', '),
    }));
    dispatch({ rows: Rows, options });
  }

  async function onOpenChange(open) {
    if (open && !props.options) await onLoadData();
    dispatch({ open });
  }

  function onSelectChange(value) {
    if (props.options) {
      onChange(value);
    } else {
      const record = state.rows.find(r => r.ID === value) || {};
      onChange(record[field], record);
    }
  }

  return <Select options={state.options} open={state.open} onOpenChange={onOpenChange} onChange={onSelectChange} {...props} />;
}